import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserInfo } from '@/types/user'
import { userApi } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>('')
  const userInfo = ref<UserInfo | null>(null)
  const isAdmin = ref<boolean>(false)

  // 从本地存储加载用户信息
  const loadFromStorage = () => {
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    
    if (storedToken) {
      token.value = storedToken
    }
    
    if (storedUserInfo) {
      userInfo.value = JSON.parse(storedUserInfo)
      isAdmin.value = userInfo.value?.user_type === 'admin'
    }
  }

  // 登录
  const login = async (username: string, password: string) => {
    try {
      console.log('发送登录请求:', { username, password })
      
      const response: any = await userApi.adminLogin({ username, password })
      console.log('登录响应:', response)
      
      // 修复：由于响应拦截器直接返回了response.data，所以不需要再访问response.data
      if (response && response.access) {
        const accessToken = response.access
        const refreshToken = response.refresh_token
        
        token.value = accessToken
        // 保存 refreshToken
        if (refreshToken) {
          localStorage.setItem('refreshToken', refreshToken)
        }
        localStorage.setItem('token', accessToken)
        
        // 设置用户信息 - 修复字段映射
        userInfo.value = {
          id: response.id || response.user_id || 0, // 后端可能没有返回id，设置默认值
          username: response.username || '',
          email: '',
          phone_number: response.phone_number || '',
          user_type: response.user_type || 'user',
          is_active: true,
          date_joined: new Date().toISOString(),
          last_login: new Date().toISOString(),
          avatar: response.avatar || ''
        }
        
        isAdmin.value = response.user_type === 'admin'
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        
        return { success: true }
      } else {
        return { success: false, message: '登录响应格式不正确' }
      }
    } catch (error: any) {
      console.error('登录失败:', error)
      // 检查错误响应
      if (error.response) {
        console.error('错误响应:', error.response)
        // 如果有详细错误信息则显示
        if (error.response.data) {
          if (error.response.data.detail) {
            return { success: false, message: error.response.data.detail }
          } else if (error.response.data.message) {
            return { success: false, message: error.response.data.message }
          } else {
            // 尝试显示字段级别的错误信息
            const errorMessages = Object.values(error.response.data).flat()
            if (errorMessages.length > 0) {
              return { success: false, message: errorMessages[0] as string }
            }
          }
        }
        return { success: false, message: error.response.data?.detail || '登录失败，请检查用户名和密码' }
      }
      // 网络错误或其他错误
      if (error.message) {
        return { success: false, message: error.message }
      }
      return { success: false, message: '网络错误，请检查网络连接' }
    }
  }

  // 手机号登录
  const phoneLogin = async (phone: string, code: string) => {
    try {
      // 修复：使用正确的字段名
      const response: any = await userApi.phoneLogin({ 
        phone_number: phone, 
        input_verification_code: code 
      })
      
      // 修复：由于响应拦截器直接返回了response.data，所以不需要再访问response.data
      if (response && response.access) {
        token.value = response.access
        // 保存 refreshToken
        if (response.refresh_token) {
          localStorage.setItem('refreshToken', response.refresh_token)
        }
        localStorage.setItem('token', response.access)
        
        // 设置用户信息 - 修复字段映射
        // 支持多种响应格式：response.user 或直接 response
        const userData = response.user || response
        
        if (userData) {
          userInfo.value = {
            id: userData.id || userData.user_id || 0,
            username: userData.username || '',
            email: '',
            phone_number: userData.phone_number || phone || '',
            user_type: userData.user_type || 'user',
            is_active: true,
            date_joined: userData.created_at || new Date().toISOString(),
            last_login: new Date().toISOString(),
            avatar: userData.avatar || ''
          }
          isAdmin.value = userData.user_type === 'admin'
          localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        }
        
        return { success: true }
      } else {
        return { success: false, message: '登录响应格式不正确' }
      }
    } catch (error) {
      console.error('手机号登录失败:', error)
      return { success: false, message: '登录失败，请检查手机号和验证码' }
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response: any = await userApi.getProfile()
      
      if (response) {
        userInfo.value = {
          id: response.id || response.user_id || 0,
          username: response.username || '',
          email: '',
          phone_number: response.phone_number || '',
          user_type: response.user_type || 'user',
          is_active: true,
          date_joined: response.created_at || new Date().toISOString(),
          last_login: new Date().toISOString(),
          avatar: response.avatar || ''
        }
        isAdmin.value = response.user_type === 'admin'
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  // 登出
  const logout = async () => {
    try {
      // 保存refreshToken到局部变量
      const refreshToken = localStorage.getItem('refreshToken')
      
      // 检查token存在性
      if (refreshToken) {
        await userApi.logout(refreshToken)
      }
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      // 清除本地存储
      token.value = ''
      userInfo.value = null
      isAdmin.value = false
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
    }
  }

  // 获取验证码
  const getVerificationCode = async (phone: string) => {
    try {
      // 修复：使用正确的字段名 phone_number
      const response: any = await userApi.getVerificationCode({ phone_number: phone })
      return { success: true, data: response }
    } catch (error) {
      console.error('获取验证码失败:', error)
      return { success: false, message: '获取验证码失败' }
    }
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      const refreshToken = localStorage.getItem('refreshToken')
      if (!refreshToken) {
        throw new Error('没有可用的刷新token')
      }
      
      const response = await userApi.refreshToken(refreshToken)
      
      // 处理字段映射：后端JWT刷新接口返回的是 access 和 refresh 字段
      if (response && response.access) {
        const newAccessToken = response.access
        const newRefreshToken = response.refresh_token
        
        // 更新token
        token.value = newAccessToken
        localStorage.setItem('token', newAccessToken)
        
        // 如果返回了新的refresh_token，也更新
        if (newRefreshToken) {
          localStorage.setItem('refreshToken', newRefreshToken)
        }
        
        console.log('Token刷新成功')
        return newAccessToken
      }
      
      throw new Error('刷新token失败')
    } catch (error) {
      console.error('刷新token失败:', error)
      throw error
    }
  }

  // 初始化时加载用户信息
  loadFromStorage()

  return {
    token,
    userInfo,
    isAdmin,
    login,
    phoneLogin,
    logout,
    getUserInfo,
    getVerificationCode,
    refreshToken
  }
})